package com.yyw.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyw.common.exception.FeignCallException;
import com.yyw.common.exception.RRException;
import com.yyw.common.utils.PageUtils;
import com.yyw.common.utils.Query;
import com.yyw.common.utils.R;
import com.yyw.gulimall.product.dao.SkuInfoDao;
import com.yyw.gulimall.product.dao.SpuInfoDao;
import com.yyw.gulimall.product.dto.SkuInfoStockDto;
import com.yyw.gulimall.product.entity.SkuImagesEntity;
import com.yyw.gulimall.product.entity.SkuInfoEntity;
import com.yyw.gulimall.product.entity.SpuInfoDescEntity;
import com.yyw.gulimall.product.feign.ware.WareFeignService;
import com.yyw.gulimall.product.service.SkuImagesService;
import com.yyw.gulimall.product.service.SkuInfoService;
import com.yyw.gulimall.product.service.SpuInfoDescService;
import com.yyw.gulimall.product.vo.item.ItemInfoVo;
import com.yyw.gulimall.product.vo.item.SaleAttrVo;
import com.yyw.gulimall.product.vo.item.SpecificationVo;
import com.yyw.gulimall.product.vo.supVo.Attr;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    private final SkuImagesService skuImagesService;

    private final SpuInfoDao spuInfoDao;

    private final SpuInfoDescService spuInfoDescService;

    private final WareFeignService wareFeignService;

    /**
     * 线程池，执行异步编排
     */
    private final ThreadPoolExecutor poolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.lambda().and(e -> {
                e.eq(SkuInfoEntity::getSkuId, key).or().like(SkuInfoEntity::getSkuName, key);
            });
        }
        if (!StringUtils.isEmpty(catelogId) && !Objects.equals("0", catelogId)) {
            queryWrapper.lambda().eq(SkuInfoEntity::getCatalogId, catelogId);
        }
        if (!StringUtils.isEmpty(brandId) && !Objects.equals("0", brandId)) {
            queryWrapper.lambda().eq(SkuInfoEntity::getBrandId, brandId);
        }
        if (!StringUtils.isEmpty(min) && !Objects.equals("0", min)) {
            queryWrapper.lambda().ge(SkuInfoEntity::getPrice, min);
        }
        if (!StringUtils.isEmpty(max) && !Objects.equals("0", max)) {
            queryWrapper.lambda().le(SkuInfoEntity::getPrice, max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据SkuId查询 商品详情信息
     * 使用异步编排
     * @param skuId
     * @return 商品详情 ItemInfoVo.class
     */
    @Override
    @Cacheable(value = "skuInfo", key = "'skuInfo-'+#root.args[0]")
    public ItemInfoVo itemInfoBySkuId(String skuId) {
        ItemInfoVo infoVo = new ItemInfoVo();

        // 1. 查询该SkuInfo
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = this.baseMapper.selectById(skuId);
            if (Objects.equals(null, skuInfo)) {
                log.error("查询商品详情信息为空," + skuId);
                throw new RRException("查询商品详情信息为空," + skuId);
            }
            infoVo.setSkuInfo(skuInfo);
            return skuInfo;
        }, poolExecutor);


        // 2. 查询Sku图片信息
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImages = skuImagesService.list(
                    new QueryWrapper<SkuImagesEntity>().lambda().eq(SkuImagesEntity::getSkuId, skuId));
            infoVo.setSkuImages(skuImages);
        }, poolExecutor);


        // 3. 查询Spu的销售组合信息
        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            List<SaleAttrVo> saleAttrVos = spuInfoDao.selectSaleAttrBySpu(res.getSpuId());
            infoVo.setSaleAttrVos(saleAttrVos);
        }, poolExecutor);


        // 4. 查询Spu 基本属性/快速展示
        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            List<SpecificationVo> specificationVos = spuInfoDao.selectBaseAttrByGropu(res.getSpuId(), res.getCatalogId());
            infoVo.setAttrs(specificationVos);
        }, poolExecutor);

        // 快速展示
        CompletableFuture<Void> quickAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            List<Attr> quickAttrs = spuInfoDao.selectQuickAttrBySpuId(res.getSpuId());
            infoVo.setQuickAttrs(quickAttrs);
        }, poolExecutor);

        // 5. 查询Spu介绍
        CompletableFuture<Void> spuInfoDescFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(res.getSpuId());
            infoVo.setSpuInfoDesc(spuInfoDesc);
        }, poolExecutor);


        // 6. 查询是否有库存
        CompletableFuture<Void> hasStockFuture = CompletableFuture.runAsync(() -> {
            boolean hasStock = false;
            try {
                R r = wareFeignService.bulkGetStock(Arrays.asList(Long.parseLong(skuId)));
                List<SkuInfoStockDto> stockDto = r.getData("data", new TypeReference<List<SkuInfoStockDto>>() {
                });
                if (!CollectionUtils.isEmpty(stockDto)) {
                    SkuInfoStockDto dto = stockDto.get(0);
                    if (Objects.equals(Long.parseLong(skuId), dto.getSkuId())) {
                        hasStock = dto.getHasStock();
                    }
                }
                infoVo.setHasStock(hasStock);
            } catch (Exception e) {
                e.printStackTrace();
                throw new FeignCallException("远程调用仓储系统获取库存失败", e);
            }
        }, poolExecutor);

        // 7. 等待所有任务完成
        try {
            CompletableFuture.allOf(imagesFuture, saleAttrFuture, baseAttrFuture, quickAttrFuture, spuInfoDescFuture, hasStockFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return infoVo;
    }

}